package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dto.OrderFromDto;
import com.example.dto.ProDto;
import com.example.dto.VipDto;
import com.example.mapper.OrderFromMapper;
import com.example.mapper.ProMapper;
import com.example.mapper.VipMapper;
import com.example.service.CountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CountServiceImpl implements CountService {
    @Autowired
    private ProMapper proMapper;
    @Autowired
    private VipMapper vipMapper;
    @Autowired
    private OrderFromMapper orderFromMapper;

    @Override
    public Map<String, Object> count() {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<VipDto> vipQW = new QueryWrapper<>();
        Long vipCount = vipMapper.selectCount(vipQW);
        map.put("vipCount", vipCount);
        QueryWrapper<ProDto> proQW = new QueryWrapper<>();
        Long proCount = proMapper.selectCount(proQW);
        map.put("proCount", proCount);
        QueryWrapper<OrderFromDto> orderQW = new QueryWrapper<>();
        Long orderCount = orderFromMapper.selectCount(orderQW);
        map.put("orderCount", orderCount);
        orderQW.select("sum(order_amount)");
        Object o = orderFromMapper.selectObjs(orderQW).get(0);
        if (o != null) {
            map.put("moneyCount", o.toString());
        } else {
            map.put("moneyCount", 0);
        }
        return map;
    }

    @Override
    public List<ProDto> proSort() {
        QueryWrapper<ProDto> proQW = new QueryWrapper<>();
        proQW.select("id","name","sold");
        proQW.orderByDesc("sold");
        proQW.last("LIMIT 10");
        List<ProDto> proSort = proMapper.selectList(proQW);
        return proSort;
    }

    @Override
    public List<OrderFromDto> vipSort() {
        QueryWrapper<OrderFromDto> orderQW = new QueryWrapper<>();
        // 选择要查询的字段，对 order_amount 进行求和
        orderQW.select("vip_id as vipId", "SUM(order_amount) as vipOrderSum");
        // 根据 vip_id 进行分组
        orderQW.groupBy("vip_id");
        List<OrderFromDto> orders = orderFromMapper.selectList(orderQW);
        for (OrderFromDto orderFromDto:orders){
            QueryWrapper<VipDto> vipQW = new QueryWrapper<>();
            vipQW.eq("id",orderFromDto.getVipId());
            VipDto vipDto = vipMapper.selectOne(vipQW);
            orderFromDto.setVipNickName(vipDto.getNickName());
        }


        return orders;
    }


}
